class lazyLoad {
    constructor(selector) {
        this.imgs = Array.from(document.querySelectorAll(selector));
        this.list_top = this.imgs.map((item) => {
            return this.getAbsTop(item)
        })
        this.bindEvent();
    }
    bindEvent() {
        window.onscroll = () => {
            throttling(this.toggleAttr.bind(this));
        }
        // window.addEventListener("scrool", () => {
        //     throttling(this.toggleAttr.bind(this));
        // })

    }
    getAbsTop(item) {
        if (item.offsetParent !== document.body) {
            return item.offsetTop + this.getAbsTop(item.offsetParent);
        }
        return item.offsetTop;
    }
    toggleAttr() {
        for (let i = 0; i < this.list_top.length; i++) {
            if (this.list_top[i] < scrollY + innerHeight) {
                let loadImg = new Image();
                loadImg.src = this.imgs[i].getAttribute("data-src");

                let img = this.imgs[i]

                loadImg.onload = function () {
                    img.src = img.getAttribute("data-src");
                }

                this.imgs.splice(i, 1)
                this.list_top.splice(i, 1)
                i--;
            }
        }
    }

}


var throttling = (function(){
    var t = null;
    return function( callback , delay = 200){
    // 如果t不是null那么我们就不允许代码执行; 
          if( t !== null ){
                return ; 
          }
          t = setTimeout( function(){
                // 放入你想要执行的代码; 
                callback();
                // 重置t;
                t = null;
          } , delay )
    }
})();